﻿CREATE TRIGGER tr_CreditLiability_Insert
ON dbo.t_CreditLiability
FOR INSERT , UPDATE, DELETE
AS

DECLARE @CountDel int,@CountIns int

SELECT @CountDel = COUNT(*) FROM deleted
SELECT @CountIns = COUNT(*) FROM inserted


IF UPDATE(_PAYMENT_PATTERN_Data) OR UPDATE(_PAYMENT_PATTERN_StartDate) OR
	 @CountIns > @CountDel -- it's an insert
BEGIN -- re-build t_1234s
	DECLARE @ID int,@CodePattern varchar(512),@StartDate smalldatetime

	SELECT @ID = ID,@CodePattern = _PAYMENT_PATTERN_Data, @StartDate = _PAYMENT_PATTERN_StartDate FROM  inserted

	DELETE t_1234s WHERE CreditLiabilityID = @ID

	INSERT INTO t_1234s
	SELECT @ID,RatingCode, Date
	FROM  credit_1234s(@CodePattern, @StartDate) credit_1234s
END

IF COLUMNS_UPDATED() > 0 OR -- it's an update 
	 @CountDel >= @CountIns -- it's a delete or update
BEGIN
	DECLARE @BorrID int SELECT @BorrID = BorrowerID FROM deleted

	EXEC s_CreditInfo_Fill @BorrID
END


